<?php

/**
 * simple string utility
 * @author Bruno Xu
 * @website http://blog.brunoxu.info
 * @version 12.09.26.1
 */
class stringtooltiny
{
	/**
	 * GB2312好像约等于CP936
	 * 从UTF-8文件过来的中文，来这里识别成CP936，把UTF-8换到CP936前面，还是识别成CP936，应该是符合了GB2312，变成CP936
	 * 
	 */
	public static function str_to_utf8($str) {
		$encodings = array("ASCII","GB2312","EUC-CN","GBK","CP936","UTF-8","EUC-JP","JIS","BIG-5","EUC-TW");
		$encode_original = mb_detect_encoding($str, $encodings);
		if (FALSE!==$encode_original && strtolower($encode_original)!="utf-8") {
			$str = mb_convert_encoding($str, "UTF-8", $encode_original);
		}
		return $str;
	}
}

/**
 * simple file utility
 * @author Bruno Xu
 * @website http://blog.brunoxu.info
 * @version 12.09.26.1
 */
class filetooltiny
{
	/**
	 * replace all winseperators
	 * @param string $folderpath
	 * @return string
	 */
	public static function replace_winseperators($folderpath)
	{
		return str_replace("\\", "/", $folderpath);
	}

	/**
	 * judge if the folderpath is ended with seperator
	 * @param string $folderpath
	 * @return boolean
	 */
	public static function is_folderpath_close_end($folderpath)
	{
		return strrpos($folderpath, "/")==(strlen($folderpath)-1);
	}

	/**
	 * get filename in the filepath
	 * @param string $filepath
	 * @return string
	 */
	public static function get_filename_from_filepath($filepath)
	{
		if (strpos($filepath, "/") !== FALSE) {
			return substr($filepath, (strrpos($filepath, "/")+1));
		}

		return "";
	}

	/**
	 * get filemajorname in filename
	 * @param string $filename
	 * @return string
	 */
	public static function get_filemajorname($filename)
	{
		if (strpos($filename, ".") !== FALSE) {
			$filename_array = explode(".",$filename);
			$filesuffix = $filename_array[(count($filename_array)-1)];
			return substr($filename, 0, (strlen($filename)-strlen($filesuffix)-1));
		}

		return $filename;
	}

	/**
	 * get filesuffix in filename or filepath
	 * @param string $filename		filename or filepath
	 * @return string
	 */
	public static function get_filesuffix($filename)
	{
		if (strpos($filename, ".") !== FALSE) {
			$filename_array = explode(".",$filename);
			return $filename_array[(count($filename_array)-1)];
		}

		return "";
	}
}

/**
 * useful image utility
 * @author Bruno Xu
 * @website http://blog.brunoxu.info
 * @version 12.09.26.1
 */
class imagetool
{
	public static $im_types = array('bmp', 'jpg', 'jpeg', 'png', 'gif');
	
	/**
	 * get images in folderpath
	 * @param string $folderpath		filename or filepath
	 * @param boolean $traverse		default true
	 * @return array
	 */
	public static function get_images($folderpath, $traverse=TRUE, $is_win_and_cnchar=FALSE)
	{
		if (! is_dir($folderpath)) {
			return FALSE;
		}

		$im_array = array();
		if (! filetooltiny::is_folderpath_close_end($folderpath)) {
			$folderpath .= "/";
		}

		if ($handle = opendir($folderpath)) {
			while (FALSE !== ($file=readdir($handle))) {
				if ($file!="." && $file!="..") {
					if (is_dir($folderpath.$file)) {
						if ($traverse) {
							$im_array_temp = self::get_images(($folderpath.$file), $traverse);
							if ($im_array_temp) {
								if ($im_array) {
									$im_array = array_merge($im_array, $im_array_temp);
								} else {
									$im_array = $im_array_temp;
								}
							}
						}
					} else {
						if (in_array(strtolower(filetooltiny::get_filesuffix($file)), self::$im_types)) {
							if ($is_win_and_cnchar) {
								array_push($im_array, stringtooltiny::str_to_utf8($folderpath.$file));
							} else {
								array_push($im_array, $folderpath.$file);
							}
						}
					}
				}
			}
			
			closedir($handle);
			
			return $im_array;
		}
	
		return FALSE;
	}

	/**
	 * imagecreatefrombmp version 1 (生成的图片变绿色)
	 * @param string $filename
	 * @return resource
	 */
	public static function imagecreatefrombmp_v1($filename)
	{
		$file = fopen( $filename, "rb" );
		$read = fread( $file, 10 );
		while( !feof( $file ) && $read != "" )
		{
			$read .= fread( $file, 1024 );
		}
		$temp = unpack( "H*", $read );
		$hex = $temp[1];
		$header = substr( $hex, 0, 104 );
		$body = str_split( substr( $hex, 108 ), 6 );
		if( substr( $header, 0, 4 ) == "424d" )
		{
			$header = substr( $header, 4 );
			// Remove some stuff?
			$header = substr( $header, 32 );
			// Get the width
			$width = hexdec( substr( $header, 0, 2 ) );
			// Remove some stuff?
			$header = substr( $header, 8 );
			// Get the height
			$height = hexdec( substr( $header, 0, 2 ) );
			unset( $header );
		}
		$x = 0;
		$y = 1;
		$image = imagecreatetruecolor( $width, $height );
		foreach( $body as $rgb )
		{
			$r = hexdec( substr( $rgb, 4, 2 ) );
			$g = hexdec( substr( $rgb, 2, 2 ) );
			$b = hexdec( substr( $rgb, 0, 2 ) );
			$color = imagecolorallocate( $image, $r, $g, $b );
			imagesetpixel( $image, $x, $height-$y, $color );
			$x++;
			if( $x >= $width )
			{
				$x = 0;
				$y++;
			}
		}
		return $image;
	}
	
	
	/**
	 * imagecreatefrombmp version 2 (有点瑕疵)
	 * @param string $filename
	 * @return resource
	 */
	public static function imagecreatefrombmp_v2($filename)
	{ 
		// Ouverture du fichier en mode binaire 
		if ( ! $f1 = @fopen ($filename, "rb")) return FALSE ; 
		// 1 : Chargement des ent?tes FICHIER 
		$FILE = unpack ( "vfile_type/Vfile_size/Vreserved/Vbitmap_offset" , fread($f1 ,14)); 
		if ( $FILE['file_type'] != 19778 ) return FALSE ; 
		// 2 : Chargement des ent?tes BMP 
		$BMP = unpack ( 'Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel' . 
				'/Vcompression/Vsize_bitmap/Vhoriz_resolution' . 
				'/Vvert_resolution/Vcolors_used/Vcolors_important' , fread ( $f1 , 40 )); 
		$BMP['colors' ] = pow ( 2 , $BMP['bits_per_pixel ' ]); 
		if ( $BMP['size_bitmap'] == 0 ) $BMP['size_bitmap']=$FILE['file_size']-$FILE['bitmap_offset']; 
		$BMP['bytes_per_pixel'] = $BMP['bits_per_pixel'] / 8 ; 
		$BMP['bytes_per_pixel2'] = ceil ( $BMP['bytes_per_pixel']); 
		$BMP['decal'] = ( $BMP['width']*$BMP['bytes_per_pixel'] / 4 ); 
		$BMP['decal'] -= floor ( $BMP['width'] * $BMP['bytes_per_pixel'] / 4 ); 
		$BMP['decal'] = 4 - ( 4 * $BMP['decal']); 
		if ( $BMP['decal'] == 4 ) $BMP['decal'] = 0 ; 
		// 3 : Chargement des couleurs de la palette 
		$PALETTE = array (); 
		if ( $BMP['colors'] < 16777216 ){ 
			$PALETTE = unpack ( 'V' . $BMP['colors'] , fread ( $f1 , $BMP['colors'] * 4 )); 
		} 
		// 4 : Cr?ation de l'image 
		$IMG = fread ( $f1 , $BMP['size_bitmap']); 
		$VIDE = chr ( 0 ); 
		$res = imagecreatetruecolor( $BMP['width'] , $BMP['height']); 
		$P = 0 ; 
		$Y = $BMP['height'] - 1 ; 
		while ( $Y >= 0 ){ 
			$X = 0 ; 
			while ( $X < $BMP['width']){ 
				if ( $BMP['bits_per_pixel'] == 24 ) 
					$COLOR = @unpack ( "V" , substr($IMG,$P,3).$VIDE ); 
				elseif ( $BMP['bits_per_pixel']== 16 ){ 
					$COLOR = unpack ( "n" , substr ( $IMG , $P , 2 )); 
					$COLOR[1] = $PALETTE[ $COLOR[ 1 ] + 1 ]; 
				}elseif ( $BMP['bits_per_pixel']== 8 ){ 
					$COLOR = unpack ( "n" , $VIDE . substr ( $IMG , $P , 1 )); 
					$COLOR[1] = $PALETTE[ $COLOR[ 1 ] + 1 ]; 
				}elseif ( $BMP['bits_per_pixel']== 4 ){ 
					$COLOR = unpack ( "n" , $VIDE . substr ( $IMG , floor ( $P ) , 1 )); 
					if (( $P * 2 ) % 2 == 0 ) 
						$COLOR[1] = ( $COLOR[1] >> 4 ) ; 
					else 
						$COLOR[1] = ( $COLOR[1] & 0x0F ); 
					$COLOR[1] = $PALETTE[ $COLOR[1] + 1 ]; 
				}elseif ( $BMP['bits_per_pixel']== 1 ){ 
					$COLOR = unpack ( "n" , $VIDE . substr ( $IMG , floor ( $P ) , 1 )); 
					if (( $P * 8 ) % 8 == 0 ) $COLOR[ 1 ] = $COLOR[ 1 ] >> 7 ; 
					elseif (( $P * 8 ) % 8 == 1 ) $COLOR[1] = ( $COLOR[1] & 0x40 ) >> 6 ; 
					elseif (( $P * 8 ) % 8 == 2 ) $COLOR[1] = ( $COLOR[1] & 0x20 ) >> 5 ; 
					elseif (( $P * 8 ) % 8 == 3 ) $COLOR[1] = ( $COLOR[1] & 0x10 ) >> 4 ; 
					elseif (( $P * 8 ) % 8 == 4 ) $COLOR[1] = ( $COLOR[1] & 0x8 ) >> 3 ; 
					elseif (( $P * 8 ) % 8 == 5 ) $COLOR[1] = ( $COLOR[1] & 0x4 ) >> 2 ; 
					elseif (( $P * 8 ) % 8 == 6 ) $COLOR[1] = ( $COLOR[1] & 0x2 ) >> 1 ; 
					elseif (( $P * 8 ) % 8 == 7 ) $COLOR[1] = ( $COLOR[1] & 0x1 ); 
					$COLOR[1] = $PALETTE[ $COLOR[1] + 1 ]; 
				}else return FALSE ; 
				imagesetpixel( $res , $X , $Y , $COLOR[ 1 ]); 
				$X ++ ; 
				$P += $BMP['bytes_per_pixel']; 
			} 
			$Y -- ; 
			$P += $BMP['decal']; 
		} 
		// Fermeture du fichier 
		fclose ( $f1 ); 
		return $res ; 
	}
	
	/**
	 * imagecreatefrombmp version 3 (it works fine)
	 * @param string $fname
	 * @return resource
	 */
	public static function imagecreatefrombmp($fname)
	{
		$buf=@file_get_contents($fname);
	
		if(strlen($buf)<54) return FALSE;
	
		$file_header=unpack("sbfType/LbfSize/sbfReserved1/sbfReserved2/LbfOffBits",substr($buf,0,14));
	
		if($file_header["bfType"]!=19778) return FALSE;
		$info_header=unpack("LbiSize/lbiWidth/lbiHeight/sbiPlanes/sbiBitCountLbiCompression/LbiSizeImage/lbiXPelsPerMeter/lbiYPelsPerMeter/LbiClrUsed/LbiClrImportant",substr($buf,14,40));
		if($info_header["biBitCountLbiCompression"]==2) return FALSE;
		$line_len=round($info_header["biWidth"]*$info_header["biBitCountLbiCompression"]/8);
		$x=$line_len%4;
		if($x>0) $line_len+=4-$x;
	
		$img=imagecreatetruecolor($info_header["biWidth"],$info_header["biHeight"]);
		switch($info_header["biBitCountLbiCompression"]){
			case 4:
				$colorset=unpack("L*",substr($buf,54,64));
				for($y=0;$y<$info_header["biHeight"];$y++){
					$colors=array();
					$y_pos=$y*$line_len+$file_header["bfOffBits"];
					for($x=0;$x<$info_header["biWidth"];$x++){
						if($x%2)
						$colors[]=$colorset[(ord($buf[$y_pos+($x+1)/2])&0xf)+1];
						else
						$colors[]=$colorset[((ord($buf[$y_pos+$x/2+1])>>4)&0xf)+1];
					}
					imagesetstyle($img,$colors);
					imageline($img,0,$info_header["biHeight"]-$y-1,$info_header["biWidth"],$info_header["biHeight"]-$y-1,IMG_COLOR_STYLED);
				}
				break;
			case 8:
				$colorset=unpack("L*",substr($buf,54,1024));
				for($y=0;$y<$info_header["biHeight"];$y++){
					$colors=array();
					$y_pos=$y*$line_len+$file_header["bfOffBits"];
					for($x=0;$x<$info_header["biWidth"];$x++){
						$colors[]=$colorset[ord($buf[$y_pos+$x])+1];
					}
					imagesetstyle($img,$colors);
					imageline($img,0,$info_header["biHeight"]-$y-1,$info_header["biWidth"],$info_header["biHeight"]-$y-1,IMG_COLOR_STYLED);
				}
				break;
			case 16:
				for($y=0;$y<$info_header["biHeight"];$y++){
					$colors=array();
					$y_pos=$y*$line_len+$file_header["bfOffBits"];
					for($x=0;$x<$info_header["biWidth"];$x++){
						$i=$x*2;
						$color=ord($buf[$y_pos+$i])|(ord($buf[$y_pos+$i+1])<<8);
						$colors[]=imagecolorallocate($img,(($color>>10)&0x1f)*0xff/0x1f,(($color>>5)&0x1f)*0xff/0x1f,($color&0x1f)*0xff/0x1f);
					}
					imagesetstyle($img,$colors);
					imageline($img,0,$info_header["biHeight"]-$y-1,$info_header["biWidth"],$info_header["biHeight"]-$y-1,IMG_COLOR_STYLED);
				}
				break;
			case 24:
				for($y=0;$y<$info_header["biHeight"];$y++){
					$colors=array();
					$y_pos=$y*$line_len+$file_header["bfOffBits"];
					for($x=0;$x<$info_header["biWidth"];$x++){
						$i=$x*3;
						$colors[]=imagecolorallocate($img,ord($buf[$y_pos+$i+2]),ord($buf[$y_pos+$i+1]),ord($buf[$y_pos+$i]));
					}
					imagesetstyle($img,$colors);
					imageline($img,0,$info_header["biHeight"]-$y-1,$info_header["biWidth"],$info_header["biHeight"]-$y-1,IMG_COLOR_STYLED);
				}
				break;
			default:
				return FALSE;
			break;
		}
		return $img;
	}

	/**
	 * 缩放图片[->加水印]->压缩生成图片
	 *
	 * @author Bruno Xu
	 * @website http://blog.brunoxu.info
	 *
	 * @param imName 源图片
	 * @param nimName 生成图片
	 * @param limitWidth 限制宽度
	 * @param limitHeight 限制高度
	 * @param markWords 水印文字
	 * @param markImage 水印图片
	 * @param fixWHRate 固定宽高比
	 * @param onlyReduce 只缩小不放大(onlyReduce为TRUE时：当图片小于限定矩形框时，不进行放大)
	 * @param fillWhite 补白
	 * @param nimQuality 生成图片质量
	 * @param limitFileSize 生成图片文件大小限制
	 * @param limitQuality 生成图片质量最低限额
	 * @param configs 其它设置
	 *
	 * @return 是否成功
	 */
	public static function resize_image_ex(
				$imName, $nimName, $limitWidth=0, $limitHeight=0,
				$markWords=null, $markImage=null,
				$fixWHRate=TRUE, $onlyReduce=FALSE, $fillWhite=FALSE,
				$nimQuality=90, $limitFileSize=204800, $limitQuality=80,
				$configs=array(
					"markWordsPosition"=>5,"xyOffsets"=>array(0,0),
					"markWordsWidth"=>0,"markWordsHeight"=>0,"markWordsAngle"=>0,
					"font"=>"myfont.ttf","fontSize"=>10,"fontColor"=>"#000000",
					"addShadow"=>1,"shadowColor"=>"#ffffff",
					"markImagePosition"=>5,"xyOffsets2"=>array(0,0),
					"markImageWidthRequired"=>0,"markImageHeightRequired"=>0
				)
			)
	{
		// init im
		$data = getimagesize($imName);
		switch ($data[2]) {
			case 1 :
				$im = imagecreatefromgif($imName);
				break;
			case 2 :
				$im = imagecreatefromjpeg($imName);
				break;
			case 3 :
				$im = imagecreatefrompng($imName);
				break;
			case 6:
				$im = self::imagecreatefrombmp($imName);
				break;
		}
		if (!isset($im) || !$im) {
			return FALSE;
		}

		// init imWidth,imHeight
		$imWidth = imagesx($im);
		$imHeight = imagesy($im);

		// init limitWidth,limitHeight
		if ($limitWidth<=0 || $limitHeight<=0) {
			$limitWidth = $imWidth;
			$limitHeight = $imHeight;
		}
		if ($limitWidth<=0 || $limitHeight<=0) {
			return FALSE;
		}

		// init nimWidth,nimHeight
		$nimWidth = $limitWidth;
		$nimHeight = $limitHeight;


		// 1.缩放图片
		if (! $fixWHRate) {//不需要锁定宽高比
			if (function_exists("imagecopyresampled")) {
				//$nim = imagecreate($nimWidth,$nimHeight);
				$nim = imagecreatetruecolor($nimWidth,$nimHeight);

				//resource dst_image, resource src_image, int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
				//意思解释：src_image中，从（src_x，src_y）开始取（src_w，src_h）大小的图，缩放到（dst_w，dst_h）大小，复制到dst_image中的（dst_x，dst_y）点位
				imagecopyresampled($nim,$im,0,0,0,0,$nimWidth,$nimHeight,$imWidth,$imHeight);
			} else {
				//$nim = imagecreate($nimWidth,$nimHeight);
				$nim = imagecreatetruecolor($nimWidth,$nimHeight);

				//参数同上面的imagecopyresampled
				imagecopyresized($nim,$im,0,0,0,0,$nimWidth,$nimHeight,$imWidth,$imHeight);
			}
		} else {//需要锁定宽高比
			$resizeRate = 1;
			$widthRate = $limitWidth / $imWidth;
			$heigthRate = $limitHeight / $imHeight;
			if ($widthRate < $heigthRate) {
				$resizeRate = $widthRate;
			} else {
				$resizeRate = $heigthRate;
			}
			if ($onlyReduce) {
				if (($imWidth < $limitWidth) && ($imHeight < $limitHeight)) {
					$resizeRate = 1;
				}
			}
			$nimWidth = round($imWidth*$resizeRate, 2);
			$nimHeight = round($imHeight*$resizeRate, 2);
	
			if ($fillWhite) {
				$nim = imagecreatetruecolor($limitWidth,$limitHeight);
	
				$white = imagecolorallocate($nim, 255, 255, 255);
				$black = imagecolorallocate($nim, 0, 0, 0);

				// 填充背景色
				imagefilledrectangle($nim, 0, 0, $limitWidth,$limitHeight, $white);

				if (function_exists("imagecopyresampled")) {
					imagecopyresampled($nim,$im,ceil(round(($limitWidth-$nimWidth)/2,2)),round(($limitHeight-$nimHeight)/2,2),0,0,$nimWidth,$nimHeight,$imWidth,$imHeight);
				} else {
					imagecopyresized($nim,$im,ceil(round(($limitWidth-$nimWidth)/2,2)),round(($limitHeight-$nimHeight)/2,2),0,0,$nimWidth,$nimHeight,$imWidth,$imHeight);
				}
			} else {
				if (function_exists("imagecopyresampled")) {
					//$nim = imagecreate($nimWidth,$nimHeight);
					$nim = imagecreatetruecolor($nimWidth,$nimHeight);
					imagecopyresampled($nim,$im,0,0,0,0,$nimWidth,$nimHeight,$imWidth,$imHeight);
				} else {
					//$nim = imagecreate($nimWidth,$nimHeight);
					$nim = imagecreatetruecolor($nimWidth,$nimHeight);
					imagecopyresized($nim,$im,0,0,0,0,$nimWidth,$nimHeight,$imWidth,$imHeight);
				}
			}
		}
	
		// 2.1加文字水印
		if ($markWords) {
			// init colors
			if (! isset($white)) {
				$white = imagecolorallocate($nim, 255, 255, 255);
			}
			if (! isset($black)) {
				$black = imagecolorallocate($nim, 0, 0, 0);
			}
			if (! isset($red)) {
				$red = imagecolorallocate($nim, 255, 0, 0);
			}
			if (! isset($gray)) {
				$gray = imagecolorallocate($nim, hexdec("CC"), hexdec("CC"), hexdec("CC"));
			}

			// init fontColor
			$fontColor = $black;
			if (strlen($configs["fontColor"]) == 7) {
				$R = hexdec(substr($configs["fontColor"],1,2));
				$G = hexdec(substr($configs["fontColor"],3,2));
				$B = hexdec(substr($configs["fontColor"],5));
				$fontColor = imagecolorallocate($nim, $R, $G, $B);
				if ($fontColor === FALSE) {
					$fontColor = $black;
				}
			}

			// init outputimWidth,outputimHeight
			$outputimWidth = imagesx($nim);
			$outputimHeight = imagesy($nim);

			// init markWidth,markHeight
			$markWidth = $configs["markWordsWidth"];
			$markHeight = $configs["markWordsHeight"];

			// init markPosX,markPosY
			$markPosX = 0;
			$markPosY = 0;

			// 准备字体
			if ($configs["font"] !== FALSE) {
				if ($configs["font"] && ! is_file($configs["font"])) {
					$configs["font"] = "";
				}
				if (! $configs["font"]) {
					$fonts = array(
						"simhei.ttf",//9.29
						"simkai.ttf",//11.2
						"simsun.ttc",//14.6
						////"msyh.ttf",//20.7
						//"msyhbd.ttf",//13.9

						//"C:/Windows/Fonts/simhei.ttf",//9.29
						//"C:/Windows/Fonts/simkai.ttf",//11.2
						//"C:/Windows/Fonts/simsun.ttc",//14.6
						////"C:/Windows/Fonts/msyh.ttf",//20.7
						//"C:/Windows/Fonts/msyhbd.ttf",//13.9
					);
	
					foreach ($fonts as $font) {
						if (is_file($font)) {
							$configs["font"] = $font;
							break;
						}
					}
				}
			}

			// calculate markWidth,markHeight if anyone is empty
			if (empty($markWidth) || empty($markHeight)) {
				if ($configs["font"]) {
					//float size, float angle, string fontfile, string text
					/*
					$ttfbbox_temp = imagettfbbox($configs["fontSize"],0,$configs["font"],$markWords);
					//huakang_girl_w5.ttf，myfont.ttf等字体下，文字[技术]报错，文字[菜园]却可以，错误信息：(Warning: imagettfbbox() [function.imagettfbbox]: any2eucjp(): something happen in D:\_soft_install\xampp\htdocs\imagetool.php on line 578)。虽然报错但是下面的步骤还是正常，唯一不正常的是得到的宽高中的宽大了很多，如这里得到的是81*21，而下面转码后不报错得到的是37*20，还有下面通过字符计数得到的是(0.872比率:32*16)，调整比率后得到(0.7比率:40*20)
					*/
					$ttfbbox_temp = imagettfbbox($configs["fontSize"],0,$configs["font"],mb_convert_encoding($markWords,"html-entities","UTF-8"));

					if ($ttfbbox_temp) {
						$markWidth = $ttfbbox_temp[2] - $ttfbbox_temp[6];
						$markHeight = $ttfbbox_temp[3] - $ttfbbox_temp[7];

						unset($ttfbbox_temp);
					}
				}
			}

			if (empty($markWidth) || empty($markHeight)) {
				$charLength = strlen($markWords);
				$cncharLength = mb_strlen($markWords,"utf-8");

				$cncharCount = ($charLength - $cncharLength)/2;
				$encharCount = $cncharLength - $cncharCount;

				$markHeight = round($configs["fontSize"]/0.7);
				$markWidth = round(($cncharCount+$encharCount/2)*$markHeight);
				//simsun.ttc(宋体)、myfont.ttf：英文字符是中文字符的一半
				//huakang_girl_w5.ttf：不等宽，i窄点，空格和i差不多，a宽点，中文比a又宽点，差不多1.5倍
			}

			// x坐标
			if ($markWidth < $outputimWidth) {
				if ($configs["markWordsPosition"]==0) {
					$markPosX = rand(0,($outputimWidth - $markWidth));
				} elseif ($configs["markWordsPosition"]==1 ||
							$configs["markWordsPosition"]==4 ||
							$configs["markWordsPosition"]==7) {
					$markPosX = 0;
				} elseif ($configs["markWordsPosition"]==2 ||
							$configs["markWordsPosition"]==5 ||
							$configs["markWordsPosition"]==8) {
					$markPosX = ($outputimWidth - $markWidth)/2;
				} elseif ($configs["markWordsPosition"]==3 ||
							$configs["markWordsPosition"]==6 ||
							$configs["markWordsPosition"]==9) {
					$markPosX = ($outputimWidth - $markWidth);
				}
			}
			// x偏移量
			$markPosX = $markPosX+$configs["xyOffsets"][0];

			// y坐标
			if ($markHeight < $outputimHeight) {
				if ($configs["markWordsPosition"]==0) {
					$markPosY = rand(0,($outputimHeight - $markHeight));
				} elseif ($configs["markWordsPosition"]==1 ||
							$configs["markWordsPosition"]==2 ||
							$configs["markWordsPosition"]==3) {
					$markPosY = 0;
				} elseif ($configs["markWordsPosition"]==4 ||
							$configs["markWordsPosition"]==5 ||
							$configs["markWordsPosition"]==6) {
					$markPosY = ($outputimHeight - $markHeight)/2;
				} elseif ($configs["markWordsPosition"]==7 ||
							$configs["markWordsPosition"]==8 ||
							$configs["markWordsPosition"]==9) {
					$markPosY = ($outputimHeight - $markHeight);
				}
			}
			// y偏移量
			$markPosY = $markPosY+$configs["xyOffsets"][1];

			// 文字转码
			//$markWords = iconv("UTF-8","EUC-JP",$markWords);
			//$markWords = mb_convert_encoding($markWords,"EUC-JP","UTF-8");
			//$markWords = iconv("UTF-8","html-entities",$markWords);//Wrong charset, conversion from `UTF-8' to `html-entities' is not allowed
			$markWords = mb_convert_encoding($markWords,"html-entities","UTF-8");//如果测试文件是ANSI编码，“莱利伯特RELIBOT”在这里变成了“RELIBOT”，UTF-8编码测试文件正常
			//$markWords = stringtooltiny::str_to_utf8($markWords);//UTF-8编码测试文件乱码
			//var_dump($markWords);die();

			if ($configs["font"]) {// 使用字体
				/*
				// 描边
				imagettftext($nim, $configs["fontSize"], $configs["markWordsAngle"],
								($markPosX+1), ($markPosY+$markHeight),
								$white, $configs["font"], $markWords);
				imagettftext($nim, $configs["fontSize"], $configs["markWordsAngle"],
								($markPosX-1), ($markPosY+$markHeight),
								$white, $configs["font"], $markWords);
				imagettftext($nim, $configs["fontSize"], $configs["markWordsAngle"],
								$markPosX, ($markPosY+$markHeight+1),
								$white, $configs["font"], $markWords);
				imagettftext($nim, $configs["fontSize"], $configs["markWordsAngle"],
								$markPosX, ($markPosY+$markHeight-1),
								$white, $configs["font"], $markWords);
				*/

				// 阴影
				if ($configs["addShadow"]) {
					$shadowColor = $white;
					if (strlen($configs["shadowColor"]) == 7) {
						$R = hexdec(substr($configs["shadowColor"],1,2));
						$G = hexdec(substr($configs["shadowColor"],3,2));
						$B = hexdec(substr($configs["shadowColor"],5));
						$shadowColor = imagecolorallocate($nim, $R, $G, $B);
						if ($shadowColor === FALSE) {
							$shadowColor = $white;
						}
					}
					imagettftext($nim, $configs["fontSize"], $configs["markWordsAngle"],
									($markPosX-2), ($markPosY+$markHeight+2),
									$shadowColor, $configs["font"], $markWords);
				}

				//图片|文字大小|偏转度|横坐标|纵坐标|文字颜色|文字类型|文字内容 (ps.字符串左下角坐标)
				imagettftext($nim, $configs["fontSize"], $configs["markWordsAngle"],
								$markPosX, ($markPosY+$markHeight),
								$fontColor, $configs["font"], $markWords);
			} else {// 不使用字体
				// 阴影
				if ($configs["addShadow"]) {
					$shadowColor = $white;
					if (strlen($configs["shadowColor"]) == 7) {
						$R = hexdec(substr($configs["shadowColor"],1,2));
						$G = hexdec(substr($configs["shadowColor"],3,2));
						$B = hexdec(substr($configs["shadowColor"],5));
						$shadowColor = imagecolorallocate($nim, $R, $G, $B);
						if ($shadowColor === FALSE) {
							$shadowColor = $white;
						}
					}
					imagestring($nim, $configs["fontSize"], ($markPosX-2), ($markPosY+2),
								$markWords,$shadowColor);
				}

				//resource image, int font, int x, int y, string s, int col (ps.字符串左上角坐标)
				imagestring($nim, $configs["fontSize"], $markPosX, $markPosY,
							$markWords,$fontColor);
			}
		}
	
		// 2.2加图片水印
		if ($markImage) {
			// init markim
			$data2 = getimagesize($markImage);
			switch ($data2[2]) {
				case 1 :
					$markim = imagecreatefromgif($markImage);
					break;
				case 2 :
					$markim = imagecreatefromjpeg($markImage);
					break;
				case 3 :
					$markim = imagecreatefrompng($markImage);
					break;
				case 6:
					$markim = self::imagecreatefrombmp($markImage);
					break;
			}

			// init outputimWidth,outputimHeight
			$outputimWidth = imagesx($nim);
			$outputimHeight = imagesy($nim);

			// init markWidth,markHeight
			$markWidth = imagesx($markim);
			$markHeight = imagesy($markim);

			// init markImageWidthRequired,markImageHeightRequired
			$markImageWidthRequired = $configs["markImageWidthRequired"];
			$markImageHeightRequired = $configs["markImageHeightRequired"];
			if (empty($markImageWidthRequired) || empty($markImageHeightRequired)) {
				$markImageWidthRequired = $markWidth;
				$markImageHeightRequired = $markHeight;
			}

			// init markPosX,markPosY
			$markPosX = 0;
			$markPosY = 0;

			// set markWidth,markHeight if anyone is empty
			if (empty($markWidth) || empty($markHeight)) {
				$markWidth = imagesx($markim);
				$markHeight = imagesy($markim);
			} else {
				
			}

			// x坐标
			if ($markWidth < $outputimWidth) {
				if ($configs["markImagePosition"]==0) {
					$markPosX = rand(0,floor($outputimWidth - $markWidth));
				} elseif ($configs["markImagePosition"]==1 ||
							$configs["markImagePosition"]==4 ||
							$configs["markImagePosition"]==7) {
					$markPosX = 0;
				} elseif ($configs["markImagePosition"]==2 ||
							$configs["markImagePosition"]==5 ||
							$configs["markImagePosition"]==8) {
					$markPosX = floor($outputimWidth - $markWidth)/2;
				} elseif ($configs["markImagePosition"]==3 ||
							$configs["markImagePosition"]==6 ||
							$configs["markImagePosition"]==9) {
					$markPosX = floor($outputimWidth - $markWidth);
				}
			}
			// x偏移量
			$markPosX = $markPosX+$configs["xyOffsets2"][0];

			// y坐标
			if ($markHeight < $outputimHeight) {
				if ($configs["markImagePosition"]==0) {
					$markPosY = rand(0,floor($outputimHeight - $markHeight));
				} elseif ($configs["markImagePosition"]==1 ||
							$configs["markImagePosition"]==2 ||
							$configs["markImagePosition"]==3) {
					$markPosY = 0;
				} elseif ($configs["markImagePosition"]==4 ||
							$configs["markImagePosition"]==5 ||
							$configs["markImagePosition"]==6) {
					$markPosY = floor($outputimHeight - $markHeight)/2;
				} elseif ($configs["markImagePosition"]==7 ||
							$configs["markImagePosition"]==8 ||
							$configs["markImagePosition"]==9) {
					$markPosY = floor($outputimHeight - $markHeight);
				}
			}
			// y偏移量
			$markPosY = $markPosY+$configs["xyOffsets2"][1];

			//水印不用调整大小时，也可以用这个，可能效果不及imagecopyresampled
			//resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h
			//imagecopy($nim, $markim, $markPosX, $markPosY, 0, 0, $markWidth, $markHeight);

			//水印不用调整大小时，也可以用这个，支持透明度设置
			//本来透明的png图片，用了这个之后，主体是淡了，但却出现了灰色背景
			//$transparent = 30;
			//imagecopymerge($nim, $markim, $markPosX, $markPosY, 0, 0, $markWidth, $markHeight, $transparent);

			if (function_exists("imagecopyresampled")) {
				imagecopyresampled($nim,$markim,$markPosX,$markPosY,0,0,$markImageWidthRequired,$markImageHeightRequired,$markWidth,$markHeight);
			} else {
				imagecopyresized($nim,$markim,$markPosX,$markPosY,0,0,$markImageWidthRequired,$markImageHeightRequired,$markWidth,$markHeight);
			}

			imagedestroy($markim);
		}

		// 3.压缩生成图片
		$filesize = 0;
		do {
			imagejpeg($nim, $nimName, $nimQuality);
			clearstatcache();//for php5.2
			$filesize = filesize($nimName);
			$nimQuality = $nimQuality - 10;
		} while ($filesize>$limitFileSize && $nimQuality>=$limitQuality);


		imagedestroy($nim);
		imagedestroy($im);

		return TRUE;
	}

	/**
	 * TODO 需验证和完善
	 * 锐化图片
	 *
	 * @param resource newim		image resource
	 * @param float sharp
	 *
	 * @return boolean
	 */
	public static function _image_sharp($newim, $sharp=0.4)
	{
		$newwidth = imagesx($newim);
		$newheight = imagesy($newim);

		//锐化--begin
		$cnt=0;
		for ($x=1; $x<$newwidth; $x+=2){
			for ($y=1; $y<$newheight; $y+=2)
			{
				$src_clr1 = imagecolorsforindex($newim, imagecolorat($newim, $x-1, $y-1));
				$src_clr2 = imagecolorsforindex($newim, imagecolorat($newim, $x, $y));
				$r = intval($src_clr2["red"]+$sharp*($src_clr2["red"]-$src_clr1["red"]));
				$g = intval($src_clr2["green"]+$sharp*($src_clr2["green"]-$src_clr1["green"]));
				$b = intval($src_clr2["blue"]+$sharp*($src_clr2["blue"]-$src_clr1["blue"]));
				$r = min(255, max($r, 0));
				$g = min(255, max($g, 0));
				$b = min(255, max($b, 0));
				if (($DST_CLR=imagecolorexact($newim, $r, $g, $b))==-1) {
					$DST_CLR = imagecolorallocate($newim, $r, $g, $b);
				}
				$cnt++;
				if ($DST_CLR==-1) {
					//die("color allocate faile at $x, $y ($cnt).");
				} else {
					imagesetpixel($newim, $x, $y, $DST_CLR);
				}
			}
		}
		//锐化--end

		return TRUE;
	}
}